/**
 * 图片定制编辑器JavaScript
 */

class CustomizeEditor {
    constructor() {
        this.canvas = null;
        this.ctx = null;
        this.currentTemplate = null;
        this.currentRegions = [];
        this.elements = [];
        this.selectedElement = null;
        this.isDragging = false;
        this.isResizing = false;
        this.isRotating = false;
        this.dragStart = { x: 0, y: 0 };
        this.zoom = 1.0;
        this.jsonData = null;
        this.projectId = PROJECT_DATA ? PROJECT_DATA.id : null;
        this.resizeHandle = null; // 当前拖拽的控制点
        this.resizeMode = null; // 调整模式: 'nw', 'ne', 'sw', 'se', 'n', 'e', 's', 'w'
        
        this.init();
    }

    init() {
        // 清理日志，只保留关键信息
        
        this.setupCanvas();
        this.setupEventListeners();
        this.setupUI();
        
        // 检查URL参数中的template_id
        const urlParams = new URLSearchParams(window.location.search);
        const presetTemplateId = urlParams.get('template_id');
        
        // 优先使用URL参数，然后是TEMPLATE_DATA
        let templateIdToLoad = null;
        
        if (presetTemplateId) {
            templateIdToLoad = presetTemplateId;
            $('#templateSelect').val(presetTemplateId);
        } else if (TEMPLATE_DATA) {
            templateIdToLoad = TEMPLATE_DATA.id;
        }
        
        // 加载模板
        if (templateIdToLoad) {
            // 延迟加载，确保DOM完全准备好
            setTimeout(() => {
                this.loadTemplate(templateIdToLoad);
            }, 100);
        }
        
        // 如果有初始数据，加载它
        if (PROJECT_DATA && PROJECT_DATA.json_config) {
            try {
                this.jsonData = JSON.parse(PROJECT_DATA.json_config);
                this.loadProjectData();
            } catch (e) {
                console.error('加载项目数据失败:', e);
            }
        }
    }

    setupCanvas() {
        this.canvas = document.getElementById('mainCanvas');
        if (!this.canvas) return;
        
        this.ctx = this.canvas.getContext('2d');
        this.canvas.width = 800;
        this.canvas.height = 600;
    }

    setupEventListeners() {
        // 模板选择
        $('#templateSelect').on('change', (e) => {
            const templateId = e.target.value;
            console.log('模板选择变化:', templateId);
            if (templateId) {
                this.loadTemplate(templateId);
            } else {
                this.clearTemplate();
            }
        });

        // JSON文件上传
        $('#jsonFile').on('change', (e) => {
            const file = e.target.files[0];
            $('#uploadJson').prop('disabled', !file);
        });

        $('#uploadJson').on('click', () => {
            this.uploadJsonFile();
        });

        // 画布事件（移除滚轮缩放）
        if (this.canvas) {
            this.canvas.addEventListener('mousedown', this.onMouseDown.bind(this));
            this.canvas.addEventListener('mousemove', this.onMouseMove.bind(this));
            this.canvas.addEventListener('mouseup', this.onMouseUp.bind(this));
            this.canvas.addEventListener('mouseleave', this.onMouseLeave.bind(this));
        }

        // 移除画布缩放控制，保持1:1比例确保区域位置准确

        // 工具按钮
        $('#fitToRegion').on('click', () => this.fitSelectedToRegion());
        $('#resetTransform').on('click', () => this.resetSelectedTransform());
        $('#deleteElement').on('click', () => this.deleteSelectedElement());

        // 保存和导出
        $('#saveProject').on('click', () => this.saveProject());
        $('#exportImage').on('click', () => this.exportImage());
        
        // 导出格式变化时显示/隐藏图层保留选项
        $('#exportFormat').on('change', (e) => {
            const format = $(e.target).val();
            const preserveLayersContainer = $('#preserveLayersContainer');
            if (format === 'tif' || format === 'tiff' || format === 'psd') {
                preserveLayersContainer.show();
                // PSD格式默认勾选保留图层
                if (format === 'psd') {
                    $('#preserveLayers').prop('checked', true);
                }
            } else {
                preserveLayersContainer.hide();
                $('#preserveLayers').prop('checked', false);
            }
        });

        // 键盘事件
        $(document).on('keydown', (e) => {
            if (e.key === 'Delete' && this.selectedElement) {
                this.deleteSelectedElement();
            }
        });
    }

    setupUI() {
        this.updateCanvasVisibility();
    }

    async loadTemplate(templateId) {
        try {
            APP_UTILS.showLoading('加载底板...');
            
            const response = await APP_AJAX.get(`/api/template/${templateId}/regions`);
            
            this.currentTemplate = response.template;
            this.currentRegions = response.regions;
            this.templateLayers = response.template_layers || [];
            
            console.log('加载的模板图层:', this.templateLayers);
            
            // 加载底板背景图片
            this.loadTemplateBackgroundImage();
            
            this.setupCanvasSize();
            this.renderCanvas();
            this.updateCanvasVisibility();
            
            APP_UTILS.hideLoading();
        } catch (error) {
            APP_UTILS.hideLoading();
            APP_UTILS.showError('加载底板失败: ' + (error.error || '未知错误'));
        }
    }

    setupCanvasSize() {
        if (!this.currentTemplate) return;
        
        // 设置合理的Canvas显示尺寸
        const maxWidth = 800;
        const maxHeight = 600;
        
        const templateWidth = this.currentTemplate.width;
        const templateHeight = this.currentTemplate.height;
        
        // 计算显示缩放比例
        const scaleX = maxWidth / templateWidth;
        const scaleY = maxHeight / templateHeight;
        const displayScale = Math.min(scaleX, scaleY, 1);
        
        // 设置Canvas的逻辑尺寸（用于绘制）
        this.canvas.width = Math.round(templateWidth * displayScale);
        this.canvas.height = Math.round(templateHeight * displayScale);
        
        // 设置CSS显示尺寸
        this.canvas.style.width = this.canvas.width + 'px';
        this.canvas.style.height = this.canvas.height + 'px';
        
        // 保存缩放比例用于坐标转换
        this.displayScale = displayScale;
        this.zoom = 1.0; // Canvas内部不再缩放
        
        // 画布尺寸设置完成
    }

    clearTemplate() {
        this.currentTemplate = null;
        this.currentRegions = [];
        this.templateBackgroundImage = null;
        this.elements = [];
        this.selectedElement = null;
        
        this.updateCanvasVisibility();
        this.updateLayersList();
        this.updatePropertiesPanel();
        
        if (this.ctx) {
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        }
        
        // 模板已清除
    }

    updateCanvasVisibility() {
        const hasTemplate = this.currentTemplate !== null;
        $('#canvasContainer .canvas-wrapper').toggle(hasTemplate);
        $('#canvasPlaceholder').toggle(!hasTemplate);
        
        // 更新工具按钮状态
        $('#fitToRegion, #resetTransform, #deleteElement').prop('disabled', !this.selectedElement);
        
        // 更新画布提示文本
        if (hasTemplate && this.currentTemplate) {
            $('#canvasPlaceholder h5').text(`${this.currentTemplate.name} 已加载`);
        } else {
            $('#canvasPlaceholder h5').text('选择底板开始编辑');
        }
    }

    async uploadJsonFile() {
        const fileInput = document.getElementById('jsonFile');
        const file = fileInput.files[0];
        
        if (!file) {
            APP_UTILS.showError('请选择文件');
            return;
        }

        if (!APP_UTILS.isValidJsonFile(file)) {
            APP_UTILS.showError('请选择有效的JSON文件');
            return;
        }

        try {
            APP_UTILS.showLoading('上传并解析中...');
            
            const response = await APP_AJAX.upload('/upload_json', file);
            
            if (response.success) {
                this.jsonData = response.data;
                this.parseJsonData();
                APP_UTILS.showSuccess('JSON文件解析成功');
            } else {
                APP_UTILS.showError(response.error || '上传失败');
            }
            
            APP_UTILS.hideLoading();
        } catch (error) {
            APP_UTILS.hideLoading();
            APP_UTILS.showError('上传失败: ' + (error.error || '未知错误'));
        }
    }

    parseJsonData() {
        if (!this.jsonData || !this.currentTemplate) return;
        
        this.elements = [];
        
        // 获取JSON中的原始底板尺寸
        let jsonBaseWidth = 1350;  // 默认值
        let jsonBaseHeight = 1350; // 默认值
        
        if (this.jsonData.surfaces && this.jsonData.surfaces[0] && this.jsonData.surfaces[0].baseImage) {
            const baseDimension = this.jsonData.surfaces[0].baseImage.dimension;
            if (baseDimension) {
                jsonBaseWidth = baseDimension.width;
                jsonBaseHeight = baseDimension.height;
            }
        }
        
        // 计算缩放比例
        const scaleX = this.currentTemplate.width / jsonBaseWidth;
        const scaleY = this.currentTemplate.height / jsonBaseHeight;
        
        console.log('底板尺寸适配:', {
            json: `${jsonBaseWidth}x${jsonBaseHeight}`,
            current: `${this.currentTemplate.width}x${this.currentTemplate.height}`,
            scale: `${scaleX.toFixed(3)}x${scaleY.toFixed(3)}`
        });
        
        // 解析surfaces中的regions
        if (this.jsonData.surfaces && this.jsonData.surfaces[0] && this.jsonData.surfaces[0].regions) {
            this.jsonData.surfaces[0].regions.forEach((region, regionIndex) => {
                if (region.elements) {
                    region.elements.forEach((element, elementIndex) => {
                        // 兼容两种字段命名格式
                        const imageUrl = element.imageUrl || element.image_url;
                        if (imageUrl) {
                            const placement = element.userPlacementData || element.user_placement_data || {};
                            const position = placement.position || {};
                            const scale = placement.scale || {};
                            const dimension = placement.dimension || {};
                            
                            console.log(`元素 ${regionIndex}-${elementIndex} 解析:`, {
                                imageUrl: imageUrl,
                                position: position,
                                dimension: dimension,
                                scale: scale,
                                rotation: placement.angleOfRotation || placement.angle_of_rotation || 0
                            });
                            
                            // 应用底板缩放比例进行位置和尺寸适配
                            const adaptedX = (position.x || 0) * scaleX;
                            const adaptedY = (position.y || 0) * scaleY;
                            const adaptedWidth = (dimension.width || 100) * scaleX;
                            const adaptedHeight = (dimension.height || 100) * scaleY;
                            
                            const customElement = {
                                id: `element_${regionIndex}_${elementIndex}`,
                                imageUrl: imageUrl,
                                regionIndex: regionIndex,
                                elementIndex: elementIndex,
                                x: adaptedX,
                                y: adaptedY,
                                width: adaptedWidth,
                                height: adaptedHeight,
                                scaleX: scale.scaleX || scale.scale_x || 1,
                                scaleY: scale.scaleY || scale.scale_y || 1,
                                rotation: placement.angleOfRotation || placement.angle_of_rotation || 0,
                                image: null,
                                loaded: false
                            };
                            
                            console.log(`适配元素 ${regionIndex}-${elementIndex}:`, {
                                original: `${position.x},${position.y} ${dimension.width}x${dimension.height}`,
                                adapted: `${adaptedX.toFixed(0)},${adaptedY.toFixed(0)} ${adaptedWidth.toFixed(0)}x${adaptedHeight.toFixed(0)}`
                            });
                            
                            this.elements.push(customElement);
                            this.loadElementImage(customElement);
                        }
                    });
                }
            });
        }
        
        this.updateLayersList();
        this.renderCanvas();
    }

    async loadElementImage(element) {
        // 直接使用代理加载，避免CORS问题
        this.loadImageViaProxy(element);
    }

    loadImageViaProxy(element) {
        try {
            const img = new Image();
            const proxyUrl = `/proxy_image?url=${encodeURIComponent(element.imageUrl)}`;
            
            img.onload = () => {
                element.image = img;
                element.loaded = true;
                this.renderCanvas();
            };
            
            img.onerror = (e) => {
                console.error('图片加载失败:', element.imageUrl);
                element.loaded = false;
                this.createPlaceholderImage(element);
            };
            
            img.src = proxyUrl;
        } catch (error) {
            console.error('图片加载异常:', error);
            element.loaded = false;
            this.createPlaceholderImage(element);
        }
    }

    createPlaceholderImage(element) {
        // 创建一个Canvas作为占位符
        const canvas = document.createElement('canvas');
        canvas.width = 200;
        canvas.height = 200;
        const ctx = canvas.getContext('2d');
        
        // 绘制占位符
        ctx.fillStyle = '#f0f0f0';
        ctx.fillRect(0, 0, 200, 200);
        
        ctx.strokeStyle = '#ccc';
        ctx.lineWidth = 2;
        ctx.strokeRect(10, 10, 180, 180);
        
        ctx.fillStyle = '#666';
        ctx.font = '14px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('图片加载失败', 100, 90);
        ctx.fillText('使用占位符', 100, 110);
        
        // 转换为图片对象
        const img = new Image();
        img.onload = () => {
            element.image = img;
            element.loaded = true;
            this.renderCanvas();
        };
        img.src = canvas.toDataURL();
    }

    renderCanvas() {
        if (!this.ctx || !this.currentTemplate) return;
        
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制底板背景
        this.ctx.fillStyle = '#ffffff';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制底板图片（如果有）
        this.renderTemplateBackground();
        
        // 绘制区域边界
        this.renderRegions();
        
        // 绘制元素
        this.elements.forEach(element => {
            if (element.loaded && element.image) {
                this.renderElement(element);
            }
        });
        
        // 绘制选中元素的控制点
        if (this.selectedElement) {
            this.renderSelectionControls(this.selectedElement);
        }
    }

    renderRegions() {
        this.ctx.strokeStyle = '#409eff';
        this.ctx.lineWidth = 2;
        this.ctx.setLineDash([5, 5]);
        
        this.currentRegions.forEach(region => {
            // 将模板坐标转换为Canvas坐标
            const x = region.x * this.displayScale;
            const y = region.y * this.displayScale;
            const width = region.width * this.displayScale;
            const height = region.height * this.displayScale;
            
            this.ctx.strokeRect(x, y, width, height);
            
            // 绘制区域标签
            this.ctx.fillStyle = '#409eff';
            this.ctx.font = `${Math.max(10, 14 * this.displayScale)}px Arial`;
            this.ctx.fillText(region.name, x + 5, y + 18 * this.displayScale);
        });
        
        this.ctx.setLineDash([]);
    }

    renderElement(element) {
        this.ctx.save();
        
        // 将元素坐标转换为Canvas坐标
        const x = element.x * this.displayScale;
        const y = element.y * this.displayScale;
        const width = element.width * element.scaleX * this.displayScale;
        const height = element.height * element.scaleY * this.displayScale;
        
        // 应用变换
        this.ctx.translate(x + width / 2, y + height / 2);
        this.ctx.rotate(element.rotation * Math.PI / 180);
        
        // 绘制图片
        this.ctx.drawImage(element.image, -width / 2, -height / 2, width, height);
        
        this.ctx.restore();
    }

    renderTemplateBackground() {
        // 绘制底板背景图片
        if (this.templateBackgroundImage && this.currentTemplate) {
            try {
                this.ctx.drawImage(
                    this.templateBackgroundImage,
                    0, 0,
                    this.canvas.width,
                    this.canvas.height
                );
                // 底板背景图片已绘制
            } catch (error) {
                console.error('绘制底板背景失败:', error);
            }
        }
    }

    loadTemplateBackgroundImage() {
        if (!this.currentTemplate || !this.currentTemplate.image_path) {
            return;
        }

        const img = new Image();
        img.crossOrigin = 'anonymous';
        
        img.onload = () => {
            this.templateBackgroundImage = img;
            this.renderCanvas();
        };
        
        img.onerror = (e) => {
            console.error('底板背景图片加载失败');
            this.templateBackgroundImage = null;
            
            // 尝试重新加载一次
            setTimeout(() => {
                const retryImg = new Image();
                retryImg.crossOrigin = 'anonymous';
                retryImg.onload = () => {
                    this.templateBackgroundImage = retryImg;
                    this.renderCanvas();
                };
                retryImg.src = `/template_image/${this.currentTemplate.id}?t=${Date.now()}`;
            }, 1000);
        };
        
        // 使用模板图片路由，添加时间戳避免缓存
        img.src = `/template_image/${this.currentTemplate.id}?t=${Date.now()}`;
    }

    renderSelectionControls(element) {
        // 将元素坐标转换为Canvas坐标
        const x = element.x * this.displayScale;
        const y = element.y * this.displayScale;
        const width = element.width * element.scaleX * this.displayScale;
        const height = element.height * element.scaleY * this.displayScale;
        
        // 绘制选择框
        this.ctx.strokeStyle = '#f56c6c';
        this.ctx.lineWidth = 2;
        this.ctx.setLineDash([]);
        this.ctx.strokeRect(x, y, width, height);
        
        // 绘制控制点（更大更明显）
        const controlSize = Math.max(8, 10);
        this.ctx.fillStyle = '#ffffff';
        this.ctx.strokeStyle = '#f56c6c';
        this.ctx.lineWidth = 2;
        
        // 存储控制点位置用于点击检测（Canvas坐标系）
        this.controlPoints = {
            nw: { x: x, y: y, cursor: 'nw-resize' },
            ne: { x: x + width, y: y, cursor: 'ne-resize' },
            sw: { x: x, y: y + height, cursor: 'sw-resize' },
            se: { x: x + width, y: y + height, cursor: 'se-resize' },
            n: { x: x + width / 2, y: y, cursor: 'n-resize' },
            s: { x: x + width / 2, y: y + height, cursor: 's-resize' },
            w: { x: x, y: y + height / 2, cursor: 'w-resize' },
            e: { x: x + width, y: y + height / 2, cursor: 'e-resize' }
        };
        
        // 控制点位置已生成
        
        // 绘制所有控制点
        Object.keys(this.controlPoints).forEach(key => {
            const point = this.controlPoints[key];
            
            // 绘制白色填充的控制点
            this.ctx.fillRect(point.x - controlSize / 2, point.y - controlSize / 2, controlSize, controlSize);
            this.ctx.strokeRect(point.x - controlSize / 2, point.y - controlSize / 2, controlSize, controlSize);
        });
    }

    onMouseHover(e) {
        if (this.isDragging) return;
        
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        if (this.selectedElement) {
            // 检查是否悬停在控制点上
            const resizeHandle = this.getResizeHandle(x, y);
            
            if (resizeHandle) {
                this.canvas.style.cursor = resizeHandle.cursor;
            } else {
                // 检查是否在元素内部
                const templateX = x / this.displayScale;
                const templateY = y / this.displayScale;
                const element = this.getElementAt(templateX, templateY);
                
                if (element === this.selectedElement) {
                    this.canvas.style.cursor = 'move';
                } else {
                    this.canvas.style.cursor = 'default';
                }
            }
        } else {
            this.canvas.style.cursor = 'default';
        }
    }

    getResizeHandle(x, y) {
        if (!this.selectedElement || !this.controlPoints) {
            return null;
        }
        
        const tolerance = 12; // 控制点检测容差
        
        for (const [key, point] of Object.entries(this.controlPoints)) {
            const distance = Math.sqrt(
                Math.pow(x - point.x, 2) + Math.pow(y - point.y, 2)
            );
            
            if (distance <= tolerance) {
                return { handle: key, cursor: point.cursor };
            }
        }
        
        return null;
    }

    onMouseDown(e) {
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        // 转换为模板坐标系（逆向缩放）
        const templateX = x / this.displayScale;
        const templateY = y / this.displayScale;
        
        // 保存当前事件，用于修饰键检测
        this.currentEvent = e;
        
        // 首先检查是否点击了控制点（使用Canvas坐标系）
        if (this.selectedElement) {
            const resizeHandle = this.getResizeHandle(x, y);
            if (resizeHandle) {
                this.isResizing = true;
                this.resizeMode = resizeHandle.handle;
                this.isDragging = true; // 也要设置为拖拽状态
                this.dragStart = { x: templateX, y: templateY };
                return;
            }
        }
        
        // 查找点击的元素（使用模板坐标）
        const clickedElement = this.getElementAt(templateX, templateY);
        
        if (clickedElement) {
            this.selectedElement = clickedElement;
            this.isDragging = true;
            this.isResizing = false; // 确保调整大小状态被重置
            this.isRotating = false; // 确保旋转状态被重置
            this.resizeMode = null; // 重置调整模式
            this.dragStart = { x: templateX, y: templateY };
            
            // 检查修饰键
            if (e.ctrlKey) {
                this.isRotating = true;
            }
            
            this.updatePropertiesPanel();
            this.updateLayersList();
            this.renderCanvas();
        } else {
            this.selectedElement = null;
            this.isDragging = false;
            this.isResizing = false;
            this.isRotating = false;
            this.resizeMode = null;
            this.updatePropertiesPanel();
            this.updateLayersList();
            this.renderCanvas();
        }
    }

    onMouseMove(e) {
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        // 更新当前事件，用于修饰键检测
        this.currentEvent = e;
        
        // 如果正在拖拽，处理拖拽逻辑
        if (this.isDragging && this.selectedElement) {
            // 转换为模板坐标系
            const templateX = x / this.displayScale;
            const templateY = y / this.displayScale;
            
            // 计算模板坐标系中的移动距离
            const deltaX = templateX - this.dragStart.x;
            const deltaY = templateY - this.dragStart.y;
            
            if (this.isResizing && this.resizeMode) {
                // 使用控制点调整大小
                this.handleResizeDrag(deltaX, deltaY, e);
            } else if (this.isRotating) {
                // 旋转
                this.selectedElement.rotation += deltaX * 0.5;
            } else {
                // 移动
                this.selectedElement.x += deltaX;
                this.selectedElement.y += deltaY;
            }
            
            this.dragStart = { x: templateX, y: templateY };
            this.renderCanvas();
            this.updatePropertiesPanel();
        } else {
            // 非拖拽状态下的悬停检测
            this.onMouseHover(e);
        }
    }

    handleResizeDrag(deltaX, deltaY, event) {
        const element = this.selectedElement;
        const originalWidth = element.width * element.scaleX;
        const originalHeight = element.height * element.scaleY;
        
        let newWidth = originalWidth;
        let newHeight = originalHeight;
        let newX = element.x;
        let newY = element.y;
        
        // 根据控制点位置调整大小
        switch (this.resizeMode) {
            case 'nw': // 左上角
                newWidth = originalWidth - deltaX;
                newHeight = originalHeight - deltaY;
                newX = element.x + deltaX;
                newY = element.y + deltaY;
                break;
            case 'ne': // 右上角
                newWidth = originalWidth + deltaX;
                newHeight = originalHeight - deltaY;
                newY = element.y + deltaY;
                break;
            case 'sw': // 左下角
                newWidth = originalWidth - deltaX;
                newHeight = originalHeight + deltaY;
                newX = element.x + deltaX;
                break;
            case 'se': // 右下角
                newWidth = originalWidth + deltaX;
                newHeight = originalHeight + deltaY;
                break;
            case 'n': // 上边
                newHeight = originalHeight - deltaY;
                newY = element.y + deltaY;
                break;
            case 's': // 下边
                newHeight = originalHeight + deltaY;
                break;
            case 'w': // 左边
                newWidth = originalWidth - deltaX;
                newX = element.x + deltaX;
                break;
            case 'e': // 右边
                newWidth = originalWidth + deltaX;
                break;
        }
        
        // 确保最小尺寸
        newWidth = Math.max(20, newWidth);
        newHeight = Math.max(20, newHeight);
        
        // 检查修饰键
        if (event && event.altKey) {
            // Alt键：自由调整（非等比），保持当前计算的尺寸
        } else if (event && event.shiftKey) {
            // Shift键：强制等比调整
            const aspectRatio = element.width / element.height;
            
            // 根据调整的主要方向决定以哪个尺寸为准
            if (['nw', 'ne', 'sw', 'se'].includes(this.resizeMode)) {
                // 角点：以较大的变化为准
                if (Math.abs(deltaX) > Math.abs(deltaY)) {
                    newHeight = newWidth / aspectRatio;
                    // 重新计算位置（对于影响位置的控制点）
                    if (this.resizeMode === 'nw') {
                        newY = element.y + (originalHeight - newHeight);
                    } else if (this.resizeMode === 'ne') {
                        newY = element.y + (originalHeight - newHeight);
                    }
                } else {
                    newWidth = newHeight * aspectRatio;
                    // 重新计算位置（对于影响位置的控制点）
                    if (this.resizeMode === 'nw') {
                        newX = element.x + (originalWidth - newWidth);
                    } else if (this.resizeMode === 'sw') {
                        newX = element.x + (originalWidth - newWidth);
                    }
                }
            } else if (['n', 's'].includes(this.resizeMode)) {
                // 上下边：以高度变化计算宽度，居中调整
                newWidth = newHeight * aspectRatio;
                newX = element.x - (newWidth - originalWidth) / 2;
            } else if (['w', 'e'].includes(this.resizeMode)) {
                // 左右边：以宽度变化计算高度，居中调整
                newHeight = newWidth / aspectRatio;
                if (this.resizeMode === 'w') {
                    newY = element.y - (newHeight - originalHeight) / 2;
                } else {
                    newY = element.y - (newHeight - originalHeight) / 2;
                }
            }
        } else {
            // 默认：等比调整（与Shift相同）
            const aspectRatio = element.width / element.height;
            
            if (['nw', 'ne', 'sw', 'se'].includes(this.resizeMode)) {
                // 角点：以较大的变化为准
                if (Math.abs(deltaX) > Math.abs(deltaY)) {
                    newHeight = newWidth / aspectRatio;
                    if (this.resizeMode === 'nw' || this.resizeMode === 'ne') {
                        newY = element.y + (originalHeight - newHeight);
                    }
                } else {
                    newWidth = newHeight * aspectRatio;
                    if (this.resizeMode === 'nw' || this.resizeMode === 'sw') {
                        newX = element.x + (originalWidth - newWidth);
                    }
                }
            } else if (['n', 's'].includes(this.resizeMode)) {
                // 上下边：以高度变化计算宽度
                newWidth = newHeight * aspectRatio;
                newX = element.x - (newWidth - originalWidth) / 2;
            } else if (['w', 'e'].includes(this.resizeMode)) {
                // 左右边：以宽度变化计算高度
                newHeight = newWidth / aspectRatio;
                newY = element.y - (newHeight - originalHeight) / 2;
            }
        }
        
        // 更新元素属性
        element.x = newX;
        element.y = newY;
        element.scaleX = newWidth / element.width;
        element.scaleY = newHeight / element.height;
    }

    onMouseUp() {
        this.isDragging = false;
        this.isResizing = false;
        this.isRotating = false;
        this.resizeMode = null;
        this.currentEvent = null;
        
        // 重置鼠标样式
        if (this.selectedElement) {
            this.canvas.style.cursor = 'move';
        } else {
            this.canvas.style.cursor = 'default';
        }
    }

    onMouseLeave() {
        // 鼠标离开画布时重置状态
        this.isDragging = false;
        this.isResizing = false;
        this.isRotating = false;
        this.resizeMode = null;
        this.currentEvent = null;
        this.canvas.style.cursor = 'default';
    }

    // 移除滚轮缩放功能

    getElementAt(x, y) {
        for (let i = this.elements.length - 1; i >= 0; i--) {
            const element = this.elements[i];
            const elementX = element.x;
            const elementY = element.y;
            const elementWidth = element.width * element.scaleX;
            const elementHeight = element.height * element.scaleY;
            
            if (x >= elementX && x <= elementX + elementWidth &&
                y >= elementY && y <= elementY + elementHeight) {
                return element;
            }
        }
        
        return null;
    }

    // 移除所有缩放方法，保持1:1比例

    updateLayersList() {
        const layersList = $('#layersList');
        
        let html = '';
        
        // 显示底板图层
        if (this.templateLayers && this.templateLayers.length > 0) {
            html += `<div class="layer-section mb-3"><h6 class="text-muted mb-2">底板图层 (原始) - 共${this.templateLayers.length}个</h6>`;
            this.templateLayers.forEach((layer, index) => {
                const indent = (layer.level || 0) * 20;
                const icon = layer.is_group ? 'bi-folder' : 'bi-image';
                const bgColor = layer.is_group ? 'bg-warning' : (layer.type === 'type' ? 'bg-info' : 'bg-primary');
                const visibleIcon = layer.visible ? 'bi-eye' : 'bi-eye-slash';
                const opacityText = layer.opacity !== undefined ? layer.opacity : 255;
                
                html += `
                    <div class="layer-item template-layer" style="margin-left: ${indent}px; border-left: ${indent > 0 ? '2px solid #dee2e6' : 'none'}; padding-left: ${indent > 0 ? '8px' : '0'};">
                        <div class="layer-preview-placeholder ${bgColor} text-white d-flex align-items-center justify-content-center" style="width: 35px; height: 35px; border-radius: 4px; font-size: 12px;">
                            <i class="bi ${icon}"></i>
                        </div>
                        <div class="layer-info flex-grow-1 ms-2">
                            <h6 class="mb-0 d-flex align-items-center" style="font-size: 13px;">
                                <i class="bi ${visibleIcon} me-1 text-muted" style="font-size: 11px;"></i>
                                ${layer.name}
                            </h6>
                            <small class="text-muted" style="font-size: 11px;">
                                ${layer.type} | 透明度: ${opacityText}
                                ${layer.width && layer.height ? ` | ${layer.width}×${layer.height}` : ''}
                            </small>
                        </div>
                    </div>
                `;
            });
            html += '</div>';
        }
        
        // 显示JSON图层
        if (this.elements.length === 0) {
            if (!this.templateLayers || this.templateLayers.length === 0) {
                layersList.html(`
                    <div class="text-muted text-center py-3">
                        <i class="bi bi-layers"></i>
                        <div>暂无图层</div>
                        <small>上传JSON文件后自动生成</small>
                    </div>
                `);
                return;
            }
        } else {
            html += '<div class="layer-section"><h6 class="text-muted mb-2">JSON图层 (新增)</h6>';
        }
         this.elements.forEach((element, index) => {
             const isSelected = element === this.selectedElement;
             const actualWidth = Math.round(element.width * element.scaleX);
             const actualHeight = Math.round(element.height * element.scaleY);
             
             // 使用代理URL显示图层预览
             const previewSrc = `/proxy_image?url=${encodeURIComponent(element.imageUrl)}`;
             
             html += `
                 <div class="layer-item ${isSelected ? 'active' : ''}" data-element-id="${element.id}">
                     <img class="layer-preview" src="${previewSrc}" alt="图层 ${index + 1}" 
                          onerror="this.src='';">
                     <div class="layer-info">
                         <h6>图层 ${index + 1}</h6>
                         <small class="text-muted">位置: ${Math.round(element.x)}, ${Math.round(element.y)}</small>
                         <small class="text-muted">尺寸: ${actualWidth}×${actualHeight}</small>
                     </div>
                 </div>
             `;
         });
         
         if (this.elements.length > 0) {
             html += '</div>';  // 关闭JSON图层区域
         }
        
        layersList.html(html);
        
        // 绑定点击事件
        $('.layer-item').on('click', (e) => {
            const elementId = $(e.currentTarget).data('element-id');
            this.selectedElement = this.elements.find(el => el.id === elementId);
            this.updateLayersList();
            this.updatePropertiesPanel();
            this.renderCanvas();
        });
    }

    updatePropertiesPanel() {
        const panel = $('#propertiesPanel');
        
        if (!this.selectedElement) {
            panel.html(`
                <div class="text-muted text-center py-3">
                    <i class="bi bi-mouse"></i>
                    <div>选择元素查看属性</div>
                    <small>点击画布中的图片元素</small>
                </div>
            `);
            return;
        }
        
        const element = this.selectedElement;
         const actualWidth = Math.round(element.width * element.scaleX);
         const actualHeight = Math.round(element.height * element.scaleY);
         
         panel.html(`
             <div class="properties-panel">
                 <div class="property-group">
                     <label class="property-label">位置 (px)</label>
                     <div class="row g-2">
                         <div class="col-6">
                             <input type="number" class="form-control form-control-sm" 
                                    id="propX" value="${Math.round(element.x)}" placeholder="X坐标">
                         </div>
                         <div class="col-6">
                             <input type="number" class="form-control form-control-sm" 
                                    id="propY" value="${Math.round(element.y)}" placeholder="Y坐标">
                         </div>
                     </div>
                 </div>
                 
                 <div class="property-group">
                     <label class="property-label">显示尺寸 (px)</label>
                     <div class="row g-2">
                         <div class="col-6">
                             <input type="number" class="form-control form-control-sm" 
                                    id="propActualWidth" value="${actualWidth}" placeholder="显示宽度">
                         </div>
                         <div class="col-6">
                             <input type="number" class="form-control form-control-sm" 
                                    id="propActualHeight" value="${actualHeight}" placeholder="显示高度">
                         </div>
                     </div>
                     <div class="form-check mt-2">
                         <input class="form-check-input" type="checkbox" id="lockAspectRatio" checked>
                         <label class="form-check-label" for="lockAspectRatio">
                             锁定宽高比
                         </label>
                     </div>
                 </div>
                 
                 <div class="property-group">
                     <label class="property-label">原始尺寸 (px)</label>
                     <div class="row g-2">
                         <div class="col-6">
                             <input type="number" class="form-control form-control-sm" 
                                    id="propWidth" value="${Math.round(element.width)}" placeholder="原始宽度">
                         </div>
                         <div class="col-6">
                             <input type="number" class="form-control form-control-sm" 
                                    id="propHeight" value="${Math.round(element.height)}" placeholder="原始高度">
                         </div>
                     </div>
                 </div>
                 
                 <div class="property-group">
                     <label class="property-label">缩放比例</label>
                     <div class="row g-2">
                         <div class="col-6">
                             <input type="number" class="form-control form-control-sm" 
                                    id="propScaleX" value="${element.scaleX.toFixed(2)}" step="0.01" min="0.1" max="5" placeholder="X缩放">
                         </div>
                         <div class="col-6">
                             <input type="number" class="form-control form-control-sm" 
                                    id="propScaleY" value="${element.scaleY.toFixed(2)}" step="0.01" min="0.1" max="5" placeholder="Y缩放">
                         </div>
                     </div>
                     <div class="mt-2">
                         <button class="btn btn-sm btn-outline-secondary" id="resetScale">
                             <i class="bi bi-arrow-clockwise me-1"></i>重置缩放
                         </button>
                         <button class="btn btn-sm btn-outline-secondary" id="uniformScale">
                             <i class="bi bi-aspect-ratio me-1"></i>等比缩放
                         </button>
                     </div>
                 </div>
                 
                 <div class="property-group">
                     <label class="property-label">旋转角度</label>
                     <div class="input-group input-group-sm">
                         <input type="number" class="form-control" 
                                id="propRotation" value="${Math.round(element.rotation)}" placeholder="角度">
                         <span class="input-group-text">°</span>
                     </div>
                     <div class="mt-2">
                         <button class="btn btn-sm btn-outline-secondary" id="rotateLeft">
                             <i class="bi bi-arrow-counterclockwise"></i> -90°
                         </button>
                         <button class="btn btn-sm btn-outline-secondary" id="rotateRight">
                             <i class="bi bi-arrow-clockwise"></i> +90°
                         </button>
                     </div>
                 </div>
             </div>
         `);
        
        // 绑定属性变更事件
        $('#propX, #propY, #propWidth, #propHeight, #propScaleX, #propScaleY, #propRotation').on('input', () => {
            this.updateElementFromProperties();
        });
        
        // 显示尺寸变更事件
        $('#propActualWidth, #propActualHeight').on('input', () => {
            this.updateElementFromActualSize();
        });
        
        // 工具按钮事件
        $('#resetScale').on('click', () => {
            this.selectedElement.scaleX = 1;
            this.selectedElement.scaleY = 1;
            this.renderCanvas();
            this.updatePropertiesPanel();
        });
        
        $('#uniformScale').on('click', () => {
            const avgScale = (this.selectedElement.scaleX + this.selectedElement.scaleY) / 2;
            this.selectedElement.scaleX = avgScale;
            this.selectedElement.scaleY = avgScale;
            this.renderCanvas();
            this.updatePropertiesPanel();
        });
        
        $('#rotateLeft').on('click', () => {
            this.selectedElement.rotation -= 90;
            this.renderCanvas();
            this.updatePropertiesPanel();
        });
        
        $('#rotateRight').on('click', () => {
            this.selectedElement.rotation += 90;
            this.renderCanvas();
            this.updatePropertiesPanel();
        });
        
        // 更新工具按钮状态
        $('#fitToRegion, #resetTransform, #deleteElement').prop('disabled', false);
    }

    updateElementFromProperties() {
        if (!this.selectedElement) return;
        
        const element = this.selectedElement;
        element.x = parseFloat($('#propX').val()) || 0;
        element.y = parseFloat($('#propY').val()) || 0;
        element.width = parseFloat($('#propWidth').val()) || element.width;
        element.height = parseFloat($('#propHeight').val()) || element.height;
        element.scaleX = parseFloat($('#propScaleX').val()) || 1;
        element.scaleY = parseFloat($('#propScaleY').val()) || 1;
        element.rotation = parseFloat($('#propRotation').val()) || 0;
        
        this.renderCanvas();
    }

    updateElementFromActualSize() {
        if (!this.selectedElement) return;
        
        const element = this.selectedElement;
        const newActualWidth = parseFloat($('#propActualWidth').val()) || element.width;
        const newActualHeight = parseFloat($('#propActualHeight').val()) || element.height;
        
        const isLocked = $('#lockAspectRatio').is(':checked');
        
        if (isLocked) {
            // 锁定宽高比，以宽度为准
            const aspectRatio = element.height / element.width;
            const newScaleX = newActualWidth / element.width;
            const newScaleY = newScaleX; // 保持比例
            
            element.scaleX = newScaleX;
            element.scaleY = newScaleY;
            
            // 更新高度输入框
            $('#propActualHeight').val(Math.round(newActualWidth * aspectRatio));
        } else {
            // 独立调整宽高
            element.scaleX = newActualWidth / element.width;
            element.scaleY = newActualHeight / element.height;
        }
        
        // 更新缩放比例输入框
        $('#propScaleX').val(element.scaleX.toFixed(2));
        $('#propScaleY').val(element.scaleY.toFixed(2));
        
        this.renderCanvas();
    }

    fitSelectedToRegion() {
        if (!this.selectedElement || this.currentRegions.length === 0) return;
        
        // 找到最近的区域
        const element = this.selectedElement;
        let closestRegion = this.currentRegions[0];
        let minDistance = Infinity;
        
        this.currentRegions.forEach(region => {
            const distance = Math.sqrt(
                Math.pow(element.x - region.x, 2) + 
                Math.pow(element.y - region.y, 2)
            );
            
            if (distance < minDistance) {
                minDistance = distance;
                closestRegion = region;
            }
        });
        
        // 适应区域
        element.x = closestRegion.x;
        element.y = closestRegion.y;
        element.width = closestRegion.width;
        element.height = closestRegion.height;
        element.scaleX = 1;
        element.scaleY = 1;
        element.rotation = 0;
        
        this.renderCanvas();
        this.updatePropertiesPanel();
    }

    resetSelectedTransform() {
        if (!this.selectedElement) return;
        
        const element = this.selectedElement;
        element.scaleX = 1;
        element.scaleY = 1;
        element.rotation = 0;
        
        this.renderCanvas();
        this.updatePropertiesPanel();
    }

    deleteSelectedElement() {
        if (!this.selectedElement) return;
        
        const index = this.elements.indexOf(this.selectedElement);
        if (index > -1) {
            this.elements.splice(index, 1);
            this.selectedElement = null;
            
            this.renderCanvas();
            this.updateLayersList();
            this.updatePropertiesPanel();
        }
    }

    async saveProject() {
        const projectName = $('#projectName').val().trim();
        const templateId = $('#templateSelect').val();
        
        if (!projectName) {
            APP_UTILS.showError('请输入项目名称');
            return;
        }
        
        if (!templateId) {
            APP_UTILS.showError('请选择底板');
            return;
        }
        
        // 使用与导出相同的数据结构
        const customizationData = {
            template_id: templateId,
            regions: {}
        };
        
        // 组织元素数据到regions结构中
        this.elements.forEach(element => {
            const regionIndex = element.regionIndex || 0;
            if (!customizationData.regions[regionIndex]) {
                customizationData.regions[regionIndex] = {
                    elements: []
                };
            }
            
            customizationData.regions[regionIndex].elements.push({
                image_url: element.imageUrl,
                user_placement_data: {
                    position: { x: Math.round(element.x), y: Math.round(element.y) },
                    dimension: { 
                        width: Math.round(element.width * element.scaleX), 
                        height: Math.round(element.height * element.scaleY) 
                    },
                    scale: { scale_x: element.scaleX, scale_y: element.scaleY },
                    angle_of_rotation: element.rotation || 0
                }
            });
        });
        
        try {
            APP_UTILS.showLoading('保存中...');
            
            const response = await APP_AJAX.post('/save_project', {
                project_id: this.projectId,
                name: projectName,
                template_id: templateId,
                json_config: customizationData
            });
            
            if (response.success) {
                this.projectId = response.project_id;
                APP_UTILS.showSuccess('项目保存成功');
            } else {
                APP_UTILS.showError(response.error || '保存失败');
            }
            
            APP_UTILS.hideLoading();
        } catch (error) {
            APP_UTILS.hideLoading();
            APP_UTILS.showError('保存失败: ' + (error.error || '未知错误'));
        }
    }

    async exportImage() {
        if (!this.currentTemplate || this.elements.length === 0) {
            APP_UTILS.showError('请先选择底板并添加图片元素');
            return;
        }
        
        // 获取用户输入的文件名
        const defaultName = $('#projectName').val().trim() || `定制作品_${new Date().toLocaleDateString()}`;
        const fileName = prompt('请输入导出文件名（不需要扩展名）:', defaultName);
        if (!fileName) return; // 用户取消
        
        const customizationData = {
            regions: {}
        };
        
        // 组织元素数据
        this.elements.forEach(element => {
            const regionIndex = element.regionIndex || 0;
            if (!customizationData.regions[regionIndex]) {
                customizationData.regions[regionIndex] = {
                    elements: []
                };
            }
            
            customizationData.regions[regionIndex].elements.push({
                image_url: element.imageUrl,
                user_placement_data: {
                    position: { x: Math.round(element.x), y: Math.round(element.y) },
                    dimension: { 
                        width: Math.round(element.width * element.scaleX), 
                        height: Math.round(element.height * element.scaleY) 
                    },
                    scale: { scale_x: element.scaleX, scale_y: element.scaleY },
                    angle_of_rotation: element.rotation || 0
                }
            });
        });
        
        try {
            APP_UTILS.showLoading('生成图片中...');
            
            // 获取选择的导出格式和图层保留选项
            const exportFormat = $('#exportFormat').val() || 'png';
            const preserveLayers = $('#preserveLayers').is(':checked') && (exportFormat === 'tif' || exportFormat === 'tiff' || exportFormat === 'psd');
            
            const response = await APP_AJAX.post('/export_image', {
                template_id: this.currentTemplate.id,
                customization_data: customizationData,
                export_format: exportFormat,
                preserve_layers: preserveLayers,
                custom_filename: fileName  // 添加自定义文件名
            });
            
            if (response.success) {
                APP_UTILS.showSuccess('图片导出成功');
                
                // 创建下载链接
                const link = document.createElement('a');
                link.href = response.download_url;
                link.download = response.export_path;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } else {
                APP_UTILS.showError(response.error || '导出失败');
            }
            
            APP_UTILS.hideLoading();
        } catch (error) {
            APP_UTILS.hideLoading();
            APP_UTILS.showError('导出失败: ' + (error.error || '未知错误'));
        }
    }

    loadProjectData() {
        // 加载已有项目数据的逻辑 - 支持两种格式
        this.elements = [];
        
        if (this.jsonData && this.jsonData.elements) {
            // 旧格式：直接的elements数组
            this.elements = this.jsonData.elements.map(elementData => ({
                id: elementData.id,
                imageUrl: elementData.imageUrl,
                regionIndex: 0,
                elementIndex: 0,
                x: elementData.x,
                y: elementData.y,
                width: elementData.width,
                height: elementData.height,
                scaleX: elementData.scaleX,
                scaleY: elementData.scaleY,
                rotation: elementData.rotation,
                image: null,
                loaded: false
            }));
        } else if (this.jsonData && this.jsonData.regions) {
            // 新格式：regions结构
            Object.keys(this.jsonData.regions).forEach(regionIndex => {
                const region = this.jsonData.regions[regionIndex];
                if (region.elements) {
                    region.elements.forEach(elementData => {
                        const placement = elementData.user_placement_data || {};
                        const position = placement.position || {};
                        const dimension = placement.dimension || {};
                        const scale = placement.scale || {};
                        
                        this.elements.push({
                            id: this.generateElementId(),
                            imageUrl: elementData.image_url,
                            regionIndex: parseInt(regionIndex),
                            elementIndex: 0,
                            x: position.x || 0,
                            y: position.y || 0,
                            width: dimension.width || 100,
                            height: dimension.height || 100,
                            scaleX: scale.scale_x || 1,
                            scaleY: scale.scale_y || 1,
                            rotation: placement.angle_of_rotation || 0,
                            image: null,
                            loaded: false
                        });
                    });
                }
            });
        }
        
        // 加载所有元素的图片
        this.elements.forEach(element => {
            this.loadElementImage(element);
        });
        
        this.updateLayersList();
    }
}

// 初始化编辑器
$(document).ready(function() {
    window.customizeEditor = new CustomizeEditor();
    
    // 初始化缓存管理
    window.editorCache = new CustomizeEditorCache(window.customizeEditor);
    
    // 尝试恢复缓存状态
    const restored = window.editorCache.restoreState();
    if (restored) {
        console.log('已恢复页面缓存状态');
    }
    
    // 启动自动保存
    window.editorCache.startAutoSave();
});
